﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.DTOs;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;

namespace MS.InformationManagement.BLL.ShippingControlTemplates
{
    public class CreateItemDevolucionListCommand : IBaseCommand
    {
        #region Fields

        IEnumerable<PlanillasDTO> _foundItems;
        List<int> _itemsId = new List<int>();

        #endregion

        #region Constructors

        public CreateItemDevolucionListCommand(IEnumerable<PlanillasDTO> foundItems)
        {
            _foundItems = foundItems;
        }

        #endregion

        #region Implemented Methods

        public void Execute()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                foreach (var entity in _foundItems)
                {

                    Devolucion element = new Devolucion
                    {
                        BibliotecaDelDocumento = entity.NombreBilioteca,
                        Copia = entity.EsCopia,
                        Dirección= entity.Direccion,
                        Email = entity.Email,
                        EnvíoActivo = true,
                        FechaDeEnvío = entity.FechaEnvio,
                        IdInternoRadicado = entity.IdInternoRadicado,
                        IdItem = entity.IdItem,
                        RemitenteDestinatario= entity.Destinatario,
                        Teléfono = entity.Telefono,
                        NoRadicado = entity.NoRadicado,
                        UsuarioAsignado = entity.UsuarioAsignado,
                        EnvioRechazo = entity.MotivoRechazo
                    };
                    dc.Devoluciones.InsertOnSubmit(element);
                    dc.SubmitChanges();
                    _itemsId.Add(element.Id.Value);
                }
            }
        }

        public void Undo()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                foreach (int id in _itemsId)
                {
                    var entity = (from item in dc.Devoluciones
                                  where item.Id == id
                                  select item).FirstOrDefault();

                    dc.Devoluciones.DeleteOnSubmit(entity);
                    dc.SubmitChanges();
                }
            }
        }

        #endregion
    }
}
